package com.yuxin.tongyi.lsll.sub;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

import android.app.AlertDialog;
import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.widget.Toast;

import com.yuxin.tongyi.lsll.common.Constants;
import com.yuxin.tongyi.lsll.common.TongyiTeaApplication;
import com.yuxin.tongyi.lsll.main.LoginActivity;
import com.yuxin.tongyi.lsll.pojo.LoginInfo;
import com.yuxin.tongyi.lsll.util.HttpRequestUtil;

/**
 * 上传service
 *
 */
public class UploadService extends Service{

	private String title;
	private String loginName;   //用户名
	private String passWord;    //密码
	private final int DOWN_ERROR = 1;  //上传失败
	private final int DOWN_OVER = 2;  //上传完成
	private final int LOGIN_ERROR = 3;
	
	
	@Override
	public void onCreate() {
		super.onCreate();
		initUserInfo();//初始化用户信息
	}
	
	/**
	 * 初始化用户信息
	 */
	private void initUserInfo() {
		try {
			TongyiTeaApplication application = (TongyiTeaApplication) this.getApplication();
			LoginInfo userInfo = (LoginInfo) application.getMap().get(Constants.GLOBAL_LOGININFO);
			if (userInfo != null) { // 登陆信息
				loginName = userInfo.getLoginName();
				passWord = userInfo.getPassword();
			}
		} catch (Exception e) {
			// 获取宝宝信息失败
		    Message msg = new Message();
		    msg.what = LOGIN_ERROR;
		    UploadService.this.uploadHandler.sendMessage(msg);
		}
	}


	/**
	 * 处理上传信息
	 */
	private Handler uploadHandler = new Handler() {
		public void handleMessage(Message msg) {
    		switch (msg.what) {
			case DOWN_ERROR:
				Toast.makeText(UploadService.this, "连接服务器失败！",
						Toast.LENGTH_SHORT).show();
				break;
			case DOWN_OVER:   //下载完成
				Toast.makeText(UploadService.this, "上传成功！",
						Toast.LENGTH_SHORT).show();
				break;
			case LOGIN_ERROR:
				Toast.makeText(UploadService.this, "获取用户信息异常,请重新登陆在试！",
						Toast.LENGTH_SHORT).show();
				break;
			default:
				break;
			}
    	};
	};
	
	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
//		UploadThread uploadThread = new UploadThread();
//		Thread thread  = new Thread(uploadThread);
//		thread.start();
		return super.onStartCommand(intent, flags, startId);
	}
	
	
	/*
	 * 上传service
	 */
	class UploadThread implements Runnable {
		private String end = "\r\n";
		private String twoHyphens = "--";
		private String boundary = "*****";
		private String message = ""; // 上传文件信息
		private String studentIds; //学生id
		private String nodeEventId; //事件id
		private String classId;  //班级id
		private Message msg;
		
		public UploadThread(String studentIds,String nodeEventId,String classId) {
			this.studentIds = studentIds;
			this.nodeEventId = nodeEventId;
			this.classId = classId;
			msg = new Message();
		}
		
		/**
		 * 模拟上传提交文件
		 */
		public void run() {
			try {
				title = URLEncoder.encode(title, "UTF-8");
				URL url = new URL(HttpRequestUtil.ServerUrl
						+ HttpRequestUtil.uploadUrl + "?loginName=" + loginName
						+ "&pwd=" + passWord + "&studentId=" + studentIds
						+ "&nodeEventId=" + nodeEventId + "&classId=" + classId
						+ "&title=" + title + "&photoPath=test");
				HttpURLConnection con = (HttpURLConnection) url
						.openConnection();
				/* 允许Input、Output，不使用Cache */
				con.setDoInput(true);
				con.setDoOutput(true);
				con.setUseCaches(false);
				/* 设置传送的method=POST */
				con.setRequestMethod("POST");
				/* setRequestProperty */
				con.setRequestProperty("Connection", "Keep-Alive");
				con.setRequestProperty("Charset", "UTF-8");
				con.setRequestProperty("Content-Type",
						"multipart/form-data;boundary=" + boundary);
				/* 设置DataOutputStream */
				DataOutputStream ds = new DataOutputStream(
						con.getOutputStream());
				ds.writeBytes(twoHyphens + boundary + end);
				ds.writeBytes("Content-Disposition: form-data; "
						+ "name=\"file1\";filename=\"" + "test.jpg" + "\""
						+ end);
				ds.writeBytes(end);
				/* 取得文件的FileInputStream */
				FileInputStream fStream = new FileInputStream(
						getExternalCacheDir().toString() + File.separator
								+ "test.jpg");
				/* 设置每次写入1024bytes */
				int bufferSize = 1024;
				byte[] buffer = new byte[bufferSize];
				int length = -1;
				/* 从文件读取数据至缓冲区 */
				while ((length = fStream.read(buffer)) != -1) {
					/* 将资料写入DataOutputStream中 */
					ds.write(buffer, 0, length);
				}
				ds.writeBytes(end);
				ds.writeBytes(twoHyphens + boundary + twoHyphens + end);

				/* close streams */
				fStream.close();
				ds.flush();

				/* 取得Response内容 */
				InputStream is = con.getInputStream();
				int ch;
				StringBuffer b = new StringBuffer();
				while ((ch = is.read()) != -1) {
					b.append((char) ch);
				}
				/* 通知handler 将Response显示于Dialog */
				if (b != null) {
					String response = b.toString().trim();
					// 获取服务器返回状态
					String status = String.valueOf(response.charAt(response
							.lastIndexOf("</resultCode>") - 1));
					if ("0".equals(status)) {
						message = "上传成功";
						msg.what = DOWN_OVER;
					} else {
						message = "上传失败";
						msg.what = DOWN_ERROR;
					}
				} else {
					msg.what = DOWN_ERROR;
					message = "服务器异常,请稍后在试";
				}
				/* 关闭DataOutputStream */
				ds.close();
			} catch (Exception e) {
				message = "上传失败";
				msg.what = DOWN_ERROR;
			}
		}
	}
}
